const http = require("http")
const { execSync } = require("child_process")
const path = require("path")
const fs = require("fs")


function deleteFolderRecusive(path) {
    if(fs.existsSync(path)) {
        fs.readdirSync(path).forEach(function(file){
            const curPath = path + "/" + file
            if(fs.statSync(curPath).isDirectory()){
                deleteFolderRecusive(curPath)
            } else {
                fs.unlinkSync(curPath)
            }
        })
        fs.rmdirSync(path);
    }
}

const resolvePost = req =>
    new Promise(resolve => {
        let chunk = "";
        req.on("data", data => {
            chunk += data;
        });
        req.on("end", () => {
            resolve(JSON.parse(chunk));
        });
    });



http.createServer(async (req, res) => {
    console.log('receive request')
    console.log(req.url)
    if (req.method === 'POST' && req.url === '/') {
        const data = await resolvePost(req);
        const projectDir = path.resolve(`./${data.repository.name}`)

        deleteFolderRecusive(projectDir)

        const cloneCommand = `git clone https://gitee.com/Harvey_Zhu/${data.repository.name}.git ${projectDir}`

        console.log(cloneCommand)

        execSync(cloneCommand,{
            stdio:'inherit',
        })

        console.log('clone success')

        fs.copyFile(path.resolve(`./Dockerfile`, path.resolve(projectDir, './Dockerfile')), () => {
            console.log("copy Dockerfile success")
        })

        fs.copyFile(path.resolve(`./.dockerignore`, path.resolve(projectDir, './.dockerignore')), () => {
            console.log("copy .dockerignore success")
        })

        execSync(`docker build . -t ${data.repository.name}-image:latest`, {
            stdio: 'inherit',
            cwd: projectDir
        })

        console.log('build success')

        execSync(`docker ps -a -f "name=^${data.repository.name}-container" --format="{{.Names}}" | xargs -r docker stop | xargs -r docker rm`, {
            stdio: 'inherit'
        })

        console.log('stop success')

        execSync(`docker run -d -p 8888:80 --name ${data.repository.name}-container  ${data.repository.name}-image:latest`, {
            stdio:'inherit',
        })
    
        console.log('deploy success')
    }
    res.end('ok')
}).listen(3000,()=>{
    console.log('server is ready')
})
